package com.example.demo.utils;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * 相关运算工具类
 */
public class MathUtils {
    /**
     * 计算百分率
     *
     * @param first 除数
     * @param second 被除数
     * @param align 矫正值
     * @return 百分率
     */
    public static String getPercent(Object first, Object second, int align) {
        BigDecimal divisor = null;
        BigDecimal dividend = null;
        if (first instanceof String) {
            divisor = new BigDecimal(first.toString());
        }
        if (second instanceof String) {
            dividend = new BigDecimal(second.toString());
        }
        if (first instanceof Number) {
            divisor = BigDecimal.valueOf(Double.parseDouble(String.valueOf(first)));
        }
        if (second instanceof Number) {
            dividend = BigDecimal.valueOf(Double.parseDouble(String.valueOf(second)));
        }
        if (null == first) {
            divisor = BigDecimal.ZERO;
        }
        if (null == second) {
            dividend = BigDecimal.ZERO;
        }
        assert dividend != null;
        assert divisor != null;
        if (dividend.compareTo(BigDecimal.ZERO) == 0) {
            return "0.00%";
        }
        BigDecimal result = divisor.divide(dividend, 10, RoundingMode.HALF_UP)
                .subtract(align == 1 ? BigDecimal.ONE : BigDecimal.ZERO).multiply(new BigDecimal(100));
        result = result.setScale(2, RoundingMode.HALF_UP);
        return result + "%";
    }

    /**
     * 计算除法
     *
     * @param first 除数
     * @param second 被除数
     * @return 除法
     */
    public static double divide(double first, double second) {
        if (second == 0.0) {
            return 0.0;
        }
        return first / second;
    }
}
